import React, {Component} from 'react';
import {Card, Icon, Toast, Bubble,Avatar} from 'weaver-mobile';
import {doReviewE9} from '../../util/rightBtn';
import * as CommonUtil from '../../util/common';
import * as SignUtil from '../../util/SignUtil';
import {toJS} from 'mobx';
import {inject, observer} from 'mobx-react';
import base from "../../util/base";
import * as AdapterConstant from "../../constants/adapter";
import * as VariableKeys from '../../constants/variableKey';
import VoicePaly from '../../public/wf-voice-playback/index';
import {openAuthDetail} from "../../util/secondAuthUtil";
import * as secondAuthTypes from "../../constants/secondAuthType";
import Reply from './Reply';
import CommentList from './CommentList';
import $ from 'jquery';
import * as EmSDK from "../../util/emSDK";
const getLabel = CommonUtil.getLabel;

const jQuery = window.jQuery;
@observer
export default class SignItem extends Component {

    constructor(props) {
        super(props);
        this.state = {
            showMoreBtn: false,
            showAllReceiveUser: false,
            checkCommunication : props.store.communicateSettingKey.isExpendCommunicate || '0',
            refRequestid : props.store.refRequestid,
            communicateSettingKey: this.getCommunicateSettingKey(props)
        }
        this.receiveUserRef = React.createRef();
    }
    getCommunicateSettingKey(props){
        let communicateSettingKey = {};
        let isMainReqeuestid = true;
        const isOpenCommunication = props.isOpenCommunication || '0';
        const isShowSignCommunicate = props.store.communicateSettingKey.isShowSignCommunicate || '0';
        const isExpendCommunicate = props.store.communicateSettingKey.isExpendCommunicate || '0';
        const  hasSubmitRight = props.store && props.store.hasSubmitRight;
        const refRequestid = props.store.refRequestid;
        const allrequestInfos = props.store.requestLogParams.allrequestInfos || {};
        for(let index = 0; index < allrequestInfos.length; index++){
            if(allrequestInfos[index].requestid == refRequestid){
                communicateSettingKey.isOpenCommunication = allrequestInfos[index].isOpenCommunication;
                communicateSettingKey.isShowSignCommunicate = allrequestInfos[index].isShowSignCommunicate;
                communicateSettingKey.isExpendCommunicate = allrequestInfos[index].isExpendCommunicate ;
                communicateSettingKey.hasSubmitRight = allrequestInfos[index].hasSubmitRight;
                isMainReqeuestid = false ;
                break;
            }
        }
        if(isMainReqeuestid){
            if(isOpenCommunication == '1'){
                communicateSettingKey.isOpenCommunication = true;
            }
            if(isShowSignCommunicate == '1'){
                communicateSettingKey.isShowSignCommunicate = true;
            }
            if(isExpendCommunicate == '1'){
                communicateSettingKey.isExpendCommunicate = true;
            }
            communicateSettingKey.hasSubmitRight = hasSubmitRight;
        }
        return communicateSettingKey;
    }


    componentWillReceiveProps(nextProps) {
        // const logid1 = this.props.info.logid;
        // const nextLogid  =  nextProps.info.logid;
        // if(logid1 !== nextLogid) {
        //     this.setState({showMoreBtn:false,showAllReceiveUser:false});
        // }
        this.setState({communicateSettingKey: this.getCommunicateSettingKey(nextProps)}, () => {
        if(this.props.store.refRequestid != this.state.refRequestid){
            this.state.refRequestid = this.props.store.refRequestid;
            this.setState({'checkCommunication': this.state.communicateSettingKey.isExpendCommunicate});
          }
        });
    }

    componentDidUpdate() {
        // const currentHeight = jQuery(this.receiveUserRef.current).height();
        // if (currentHeight > 40 && !this.state.showAllReceiveUser) {
        //     this.setState({showMoreBtn: true});
        // }
    }

    componentDidMount() {
      window.openlocation = this.openlocation;
    }
    render() {
        const {info, forward, store:{loading}} = this.props;
        const {
            logid,userimg = '', displaydepname, displayname, img_path, log_remarkHtml,
            speechAttachmetnDatas = [], annexdocs = [], signdocs = [], signwfs = [], isReference, remarkLocation = '',signnaturImgHeight,
            hasCommunicationQuote
        } = info;
        const { communicateSettingKey:{isOpenCommunication,isShowSignCommunicate,isExpendCommunicate,hasSubmitRight},checkCommunication } = this.state;
        const locationInfoData = SignUtil.getLocationInfoData(remarkLocation);
        return (
            <Card full>
                <Card.Header
                    className="cardHeader"
                    title={this.getHeaderInfo(info)}
                    thumb={info.displaytype == '0' ? <Avatar userId = {info.displayid}/> : img_path}
                    thumbStyle={{borderRadius: '50%', width: '40px', height: '40px'}}
                />
                <Card.Body className="cardBody">
                    <div className={'content-right-remark-html'}
                         dangerouslySetInnerHTML={{__html: SignUtil.getRemarkHtml(log_remarkHtml)}}></div>
                    {
                        speechAttachmetnDatas &&
                        speechAttachmetnDatas.map((r,audioIndex) => {
                            return (
                               <VoicePaly key={`audio_${logid}_${audioIndex}`} datasrc = {r} />
                            )
                        })
                    }
                    <div className='remark-content-resource'>
                        {
                            annexdocs.length > 0 &&
                            <div className={'remark-content-resource-type'}>
                                <Icon type='enclosure' size={'xxs'}/>
                                <div className="content-rignt-main">
                                    {annexdocs.map((d = {}, index) => {
                                        const {filelink = '', tempshowname = '', fileExtendName = '', downloadlink = '', docImagefileSize} = d;
                                        return <div className={'content-resource-item'}
                                                    onClick={() =>{
                                                        let fileObj = {
                                                            imagefileid:d.docImagefileid,
                                                            fileExtendName:fileExtendName,
                                                            isPreViewImg:false,
                                                        }
                                                        CommonUtil.showFormAttach(fileObj,{},'/req');
                                                    }}
                                                    key={`fj_${index}`}>{`${tempshowname}.${fileExtendName}`}</div>
                                    })}
                                </div>
                            </div>
                        }
                        {
                            signdocs.length > 0 &&
                            <div className={'remark-content-resource-type'}>
                                <Icon type='blog-normal' size={'xxs'}/>
                                <div className="content-rignt-main">
                                    {signdocs.map((d = {}, index) => {
                                        return <div className={'content-resource-item'} key={`doc_${index}`}
                                                    onClick={() => {
                                                        CommonUtil.showFormDoc(d.showid, {}, '/req')
                                                    }}>{d['tempshowname']}</div>
                                    })}
                                </div>
                            </div>
                        }
                        {
                            signwfs.length > 0 &&
                            <div className={'remark-content-resource-type'}>
                                <Icon type='process' size={'xxs'}/>
                                <div className="content-rignt-main">
                                    {signwfs.map((w = {}, index) => {
                                        return <div className={'content-resource-item'} key={`wf_${index}`}
                                                    onClick={() => {
                                                        CommonUtil.showFormReq(w.requestid, {
                                                            requestid: w.requestid,
                                                            isrequest: w.isrequest
                                                        }, '/req')
                                                    }}>{w['title']}</div>
                                    })}
                                </div>
                            </div>
                        }
                        {Object.keys(locationInfoData).length > 0 &&
                            <div className={'remark-content-resource-type'}>
                                <Icon type='location' size={'xxs'}/>
                                <div className="content-rignt-main">
                                    <div className={'content-resource-item wf-sign-url'} key={`location`} onClick={() => {
                                        this.openlocation(remarkLocation)
                                    }}>{locationInfoData.address}</div>
                                </div>
                            </div>
                        }
                    </div>

                    {
                        this.getUserImg(info)
                    }

                    {
                      /* 使用getUserImg统一处理数据保护和个人签名的标识
                      userimg &&
                        <div>
                            <img style={{'maxHeight':`${signnaturImgHeight}px`}} src={userimg} />
                        </div>*/
                    }
                    {this.getReceiveCom(info)}
                </Card.Body>
                <Card.Footer className="cardFooter" content={
                    [<div className="footerBotton">
                      {isOpenCommunication  && hasSubmitRight && <div className={'btn'} onClick={() => {this.replyClick()}}>
                          <Icon type={'blog-comment'} size={'xxs'}/>
                          <span className={'btn-title'}>{getLabel('385534', "回复")}</span>
                        </div>}
                         
                        {isReference && <div className={'btn'} onClick={() => {
                            this.quoteClick()
                        }}>
                            <Icon type={'quote'} size={'xxs'}/>
                            <span className={'btn-title'}>{getLabel('19422', "引用")}</span>
                        </div>}
                        {forward == '1' && <div className={'btn'} onClick={() => {
                            this.forward()
                        }}>
                            <Icon type={'forward'} size={'xxs'}/><span
                            className={'btn-title'}>{getLabel('6011', "转发")}</span>
                        </div>
                        }
                    </div>,
                    <div>
                      {
                        isShowSignCommunicate
                        && hasCommunicationQuote 
                            ? (checkCommunication == '1')
                              ? <div 
                                  className={isExpendCommunicate ? 'communication-folder-panel open': 'communication-folder-panel'}
                                  onClick={() => {this.clickCheckCommunication()}}
                                >
                                    <span className='word-span'>{getLabel('519615', '收起交流')} </span>
                                    <Icon type="up-o" size={'xs'} />
                                </div>
                              :<div 
                                className='communication-folder-panel' 
                                onClick={() => {this.clickCheckCommunication()}}
                              >
                                  <span className='word-span'> {getLabel( '519614', '展开交流')}</span>
                                  <Icon type="down-o" size={'xs'} />
                                </div>
                            : ''
                        }
                        {
                          isShowSignCommunicate
                          && !loading  
                          && ( checkCommunication == '1')
                          && hasCommunicationQuote 
                          && <CommentList signId={logid} hasSubmitRight ={hasSubmitRight}/>
                        }
                    </div>
                    ]
                }/>
            </Card>
        )
    }

    changeCheckCommunication = () => {
      if(this.state.checkCommunication == '0') {
        this.setState({checkCommunication: '1'});
      } else {
        this.setState({checkCommunication: '0'});
      }
    }
    
    clickCheckCommunication = () => {
      const { communicateSettingKey:{hasSubmitRight,isOpenCommunication,isShowSignCommunicate,isExpendCommunicate} } = this.state;
      if(isExpendCommunicate) {
        this.setState({communicateSettingKey:{hasSubmitRight:hasSubmitRight,isOpenCommunication:isOpenCommunication,isShowSignCommunicate:isShowSignCommunicate,isExpendCommunicate:false}});
      } else {
        this.setState({communicateSettingKey:{hasSubmitRight:hasSubmitRight,isOpenCommunication:isOpenCommunication,isShowSignCommunicate:isShowSignCommunicate,isExpendCommunicate:true}});
      }
      this.changeCheckCommunication();
    }
    //接收人信息
    getReceiveCom(info = {}) {
        const {log_operatedate, log_operatetime, log_nodename, operationname, receiveUser = '', logid} = info;
        const {showMoreBtn, showAllReceiveUser} = this.state;
        let receiveUserClass = 'receive-user receive-user-more';
        let signItemReceiveAppendStyle = {};
        if (showMoreBtn && !showAllReceiveUser) {
            receiveUserClass = 'receive-user receive-user-more';
            signItemReceiveAppendStyle.paddingBottom = '10px';
        }
        return (
            <div className={'sign-item-receive'} style={signItemReceiveAppendStyle}>
                <div
                    className={'receive-time'}>{`${log_operatedate}  ${log_operatetime} [${log_nodename}/${operationname}]`}</div>
                <div ref={this.receiveUserRef} className={receiveUserClass}>
                    {`${getLabel('15525', "接收人")}：${receiveUser.replace(/,/g, ' ')}`}
                </div>
                {showMoreBtn && <div className={'show-more'}
                                     onClick={() => this.setState({showAllReceiveUser: true, showMoreBtn: false})}>
                    <div className={'show-more-btn'}>
                        <Icon type={'arrow-down-o'}/>
                        <span className={'title'}>点击显示全部</span>
                    </div>
                </div>
                }
            </div>
        )
    }

    //打开位置
    openlocation(remarkLocation = '') { //与pc端统一调用传参为str
        const locationInfoData = SignUtil.getLocationInfoData(remarkLocation);
        const {Adapter} = base.allStores.wfSignInputStore;
        // if (Adapter && Adapter.judgeApiSupport(AdapterConstant.API_OPEN_LOCATION)) {
            Adapter.openLocation(locationInfoData);
        // }
    }

    //头部的信息
    getHeaderInfo = (info) => {
        const {displayname, displaydepname,isexsAgent,displaybyagentname, log_agentorbyagentid, displayid, displaytype} = info;
        return (
            <div className={'sign-item-top'}>
                <div className={'user-name'}>
                    {isexsAgent && <span><span className={"user-name-click"} onClick={()=>{CommonUtil.formOpenHrmCard(log_agentorbyagentid)}}>{displaybyagentname}</span><span>-></span></span>}
                    <span className={"user-name-click"} onClick={() => {
                        if('1' == displaytype) {
                            CommonUtil.formOpenCrmCard(displayid)
                        } else {
                            CommonUtil.formOpenHrmCard(displayid)
                        }
                    }}>{displayname}</span>
                </div>
                <div className={'user-dept'}>{displaydepname}</div>
            </div>
        )
    }

    //签字意见回复
    replyClick() {
      const { comSetStoreState, store:{setState,recordReplyInfo, isSubReqeuestid} } = this.props;
      const { communicateSettingKey:{isShowSignCommunicate} } = this.state;
      const { info={}, setSignReply, setTabKey } = this.props;
      if(!isShowSignCommunicate && isSubReqeuestid() == 0) {
        comSetStoreState({relatedPage: '1', 
                          page: 'allCommunications',
                          needPanel: true,
                        });
        setTabKey('communicate'); //点击回复直接跳转至相关交流页面
        setSignReply(true, info); //将回复人的信息放在globalStore中
      } else {
        setState({showReply: true});
        recordReplyInfo(info);
        EmSDK.resetBottomBtn();
      }
    }

   


    //转发
    forward() {
        const {info, forward} = this.props;
        const {displayid, displayname, img_path} = info;
        doReviewE9({id: displayid, name: displayname, messagerurl: img_path});
    }

    quoteClick() {
        const {info = {}, forward} = this.props;
        let {logid, isexsAgent, displaybyagentname, displayname, displaydepname, log_operatedate, log_operatetime, log_remarkHtml = ''} = info;

        const {controlVariableMap, variableMap,showSignInput} = base.allStores.wfSignInputStore;
        let remarkQuoteList = SignUtil.getVariableMapVal(VariableKeys.SIGN_REMARK_QUOTE, []);

        let title = getLabel('19422', "引用");
        if (isexsAgent) {
            title += `<font style="margin:0 10px;color:#4D7AD8" >${displaybyagentname}->${displayname}</font>`;
        } else {
            title += `<font style="margin:0 10px;color:#4D7AD8">${displayname}</font>`;
        }
        title += `${displaydepname}  ${log_operatedate} ${log_operatetime}`;
        log_remarkHtml = log_remarkHtml.replace(/<span style='font-size:11px;color:#666;'>/g, "<span style='font-size:11px;color:#666;' _quote='true'>");
        let container__ = `<div class='container_form_wrap' style="color:#333">` +
            `<span class='container_form_wrap_span'>${title}</span>` +
            `<div _quotoContent='true' style='color:#333;line-height:normal;overflow-x: auto;'>${log_remarkHtml}</div>` +
            `</div>`;
        let flag = true;
        remarkQuoteList.map((v) => {
            if (v == container__) {
                Bubble.warning(getLabel(500249,'不能重复引用'), 1);
                flag = false;
            }
        })
        if (flag) {
            remarkQuoteList.push(container__);
            typeof controlVariableMap === 'function' && controlVariableMap(VariableKeys.SIGN_REMARK_QUOTE, remarkQuoteList);

            const showSignArea = SignUtil.getVariableMapVal(VariableKeys.SHOW_SIGN_AREA,false);
            if(!showSignArea) {
                showSignInput();
            }
        }
    }

    //下载
    download(url) {
        // jQuery('#WfFormFileDownload').attr('src',url);
    }

    getUserImg(info) {
        const {secondAuthDetail} = this.props;
        const {logid, qys_signature_id = "", userimg, signnaturImgHeight, clickCheck = 0,qyswidth = 0,qysheight = 0} = info;
        let imgstyle = {};
        if( qyswidth> 0 && qysheight > 0){
            imgstyle.width = qyswidth;
            imgstyle.height = qysheight;
        }
        let checkClassName = "";
        const {checkResult} = secondAuthDetail;
        const maxHeightStyle= signnaturImgHeight == -1 ? 'none' : signnaturImgHeight+'px';
        if (checkResult.has(logid)) {
            const result = checkResult.get(logid);
            const {isProtected, checkSuccess, protectType} = result;

            if (isProtected == 1) {
                if (protectType == secondAuthTypes.CA_AUTH) {     //CA认证
                    checkClassName += "content-right-ca-auth";
                } else if (protectType == secondAuthTypes.QYS) {     //契约锁
                    if(!!qys_signature_id  || userimg){
                        checkClassName += "content-right-qys-signature";
                    }else {
                        checkClassName += "content-right-qys-auth";
                    }
                }

                if (checkSuccess == "1") {
                    if (protectType == secondAuthTypes.CA_AUTH) {
                        checkClassName += " content-right-ca-auth-success";
                    } else if (protectType == secondAuthTypes.QYS) {
                        if (!!qys_signature_id || userimg) {
                            checkClassName += " content-right-qys-signature-success";
                        } else {
                            checkClassName += " content-right-qys-auth-success";
                        }
                    }
                } else if (checkSuccess == "2") {
                    if (protectType == secondAuthTypes.CA_AUTH) {
                        checkClassName += " content-right-ca-auth-failed";
                    } else if (protectType == secondAuthTypes.QYS) {
                        if (!!qys_signature_id || userimg) {
                            checkClassName += " content-right-qys-signature-failed";
                        } else {
                            checkClassName += " content-right-qys-auth-failed";
                        }
                    }
                }

                if(protectType == secondAuthTypes.QYS) {
                    if (!!qys_signature_id) {   //有契约锁的个人签名
                        return (
                            <div className={checkClassName} onClick={this.checkAuthDetail.bind(this, logid, clickCheck, false)}>
                                <img src={`/weaver/weaver.file.FileDownload?fileid=${qys_signature_id}`}  {...imgstyle}/>
                                <div/>
                            </div>
                        );
                    } else if (userimg) {      //使用个人签章
                        return (
                            <div className="content-right-userimg" style={{'maxHeight': `${maxHeightStyle}`}} >
                                <img style={{'maxHeight': `${maxHeightStyle}`}} src={userimg} onClick={this.checkAuthDetail.bind(this, logid, clickCheck, false)}/>
                                <div/>
                            </div>
                        );
                    }
                }

                //没有签章用默认的样式
                return <div className={checkClassName} onClick={this.checkAuthDetail.bind(this, logid,clickCheck,false)}/>
            }else {     //没有数据保护
                if (!!qys_signature_id) {       //说明有契约锁认证
                    return (
                        <div className="content-right-userimg" onClick={this.checkAuthDetail.bind(this, logid, 0,true)}>
                            <img src={`/weaver/weaver.file.FileDownload?fileid=${qys_signature_id}`}  {...imgstyle}/>
                        </div>
                    );
                }
            }
        }

        if (userimg) {
            return (
                <div>
                    <img style={{'maxHeight': `${maxHeightStyle}`}} src={userimg}/>
                </div>
            );
        } else {
            return null;
        }
    }

    /**
     *
     * @param logid 日志id
     * @param clickCheck 点击时是否需要验证，1：需要，0：不需要
     * @param isAuth 是否是契约锁二次认证
     */
    checkAuthDetail(logid, clickCheck, isAuth = false) {
        const {secondAuthDetail} = this.props;
        const {wfGlobalStore} = base;
        const {commonParam} = wfGlobalStore;

        if (clickCheck == 1) {
            secondAuthDetail.setCommonParam(commonParam);
            secondAuthDetail.checkProtectDatas(logid).then(data => {
                const {success, message} = data;

                const checkSuccess = success;
                secondAuthDetail.setCheckResult(logid, {checkSuccess});
                //success:0验证出错，1：未被篡改，2：被篡改
                if (success == "1" || success == "2") {
                    openAuthDetail(logid, isAuth);      //打开验证的详情的页面
                }
            });
        } else {
            openAuthDetail(logid, isAuth);      //打开验证的详情的页面
        }
    }
}